<?php
class XA_Model_Tempfile extends XA_Model {


	protected function getLocation($id) {
		return TEMPORARY_PATH.$this->session[$id]['year'].'/'.$this->session[$id]['month'].'/'.$this->session[$id]['day'].'/'.$id;
	}


	public function create($name) {
		mt_srand();
		$file_id = md5($name.time().mt_rand());
		$this->session[$file_id] = array(
			  'year' => date('Y')
			, 'month' => date('m')
			, 'day' => date('d')
			, 'name' => $name
		);

		$file_save_path = $this->getLocation($file_id);
		if (!is_writable(dirname($file_save_path))) {
			if (!mkdir(dirname($file_save_path), 0777, true)) {
				trigger_error('Could not create directory '.dirname($file_save_path), E_USER_ERROR);
				return false;
			}
		}
		return $file_id;
	}


	public function add($name, $path) {
		if (is_readable($path)) {
			$file_save_path = $this->getLocation($file_id = $this->create($name));
			if (is_uploaded_file($path)) {
				move_uploaded_file($path, $file_save_path);
			} else {
				copy($path, $file_save_path);
			}
			return $file_id;
		}
		return false;
	}


	public function remove($id) {
		unlink($this->getLocation($id));
	}


	public function get($id) {
		$return = $this->session[$id];
		$return['location'] = $this->getLocation($id);
		return $return;
	}
}
